<?php
/**
 * @file
 */

/**
 * Menu callback function
 */
function wordgame_mainpage() {
  // If there is a menu link to this nodejschat, the link becomes the last part
  // of the active trail, and the link name becomes the page title.
  // Thus, we must explicitly set the page title to be the nodejschat title.
  drupal_set_title(NULL);   
  $build = array(
    '#theme' => 'wordgame_page',
    '#attached' => array(
      'css' => array(drupal_get_path('module', 'wordgame') . "/css/wordgame.css"),
      'js' => array(drupal_get_path('module', 'wordgame') . "/wordgame.js")
    )
  );  
  
  $build['header'] = wordgame_page_header_element();
  
  $user_level = wordgame_user_level();
  $wordgame = NULL;
  
  if (!wordgame_access('access game')) {    
    $build['content']['user_login'] = drupal_get_form('user_login');    
  }
  else {
    if (!$user_level) {
      $build['content']['user_level'] = drupal_get_form('wordgame_level');
    } 
    else {
      $wordgame = wordgame_latest_games();
    }   
  }
  
  if ($wordgame) {
    $uri = entity_uri('wordgame', $wordgame);
    // Set the nodejschat path as the canonical URL to prevent duplicate content.
    drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
    // Set the non-aliased path as a default shortlink.
    drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  
    $build['content']['board'] = wordgame_view($wordgame);
    // Show words
    $build['footer']['words'] = array(
      '#type' => 'item',
      '#title' => t('Words'),
      '#markup' => implode(" ", array_keys($wordgame->words))
    );
  }

  return $build;
}

/**
 * User menu
*/
function wordgame_page_header_element() {
  $build = array();
  if (!wordgame_access('access game')) {
    $build['login'] = array(
      '#type' => 'markup',
      '#markup' => t('Login'),
      '#prefix' => '<span class="center">',
      '#suffix' => '</span>',
    );
    return $build;
  }
  else {
    $user_level = wordgame_user_level();
      if (!$user_level) {
        $build['level'] = array(
        '#type' => 'markup',
        '#markup' => t('Choose level'),   
        '#prefix' => '<span class="center">',
        '#suffix' => '</span>',     
      );
      return $build;
    }
    $build['game'] = array(
      '#type' => 'container',
      'wgid' => array('#markup' => t('Wordgame: <span class="wgid">@wgid</span>', array('@wgid' => $user_level->played))),
      '#attributes' => array('class' => array('wordgame-text'))
    );
    $build['points'] = array(
      '#type' => 'container',
      'points' => array('#markup' => t('Scores: <span class="total-points">@point</span>', array('@point' => $user_level->point))),
      '#attributes' => array('class' => array('wordgame-text'))
    );
    $build['menu'] = array(
      '#theme' => 'item_list',
      '#items' => array(
        array('data' => l(t('Contact'), 'contact')),
        array('data' => l(t('Skip'), 'wordgame/skip')),
        array('data' => l(t('New game'), 'wordgame/level')),
        array('data' => l(t('Logout'), 'user/logout'))
      ),
      '#attributes' => array('class' => array('wordgame-menu'))
    );
  }
  return $build;
}

/**
 * Menu callback function
 */
function wordgame_guest() {
  if (!wordgame_access('access game')) {
    exit;
  }
  global $user;
	$wordgame = wordgame_load_by_uid($user->uid);
	$position = $_GET['position'];
	$char = strtolower($_GET['char']);
	$guests = $wordgame->guests;
  $push_message = (object) array(
    'channel' => 'wordgame_' . $wordgame->wgid,
    'callback' => 'wordgameUpdateBoard',
    'data' => array(
      'wgid' => $wordgame->wgid,
      'sid' => $wordgame->sid,
      'col' => $position['col'],
      'row' => $position['row'],
      'char' => $char,
      'result' => FALSE,
      'finished' => FALSE
    ),
  );
	if ($guests[$position['row']][$position['col']]['letter'] == $char) {
    $wordgame->results[$position['row']][$position['col']] = $char;
    $wordgame->amounts[$char] = $wordgame->amounts[$char] - 1;
    unset($wordgame->guests[$position['row']][$position['col']]);
    $wordgame->guests = array_filter($wordgame->guests);
    // Send message to client
    $push_message->data['result'] = TRUE;
    $push_message->data['amount'] = $wordgame->amounts[$char] ? $wordgame->amounts[$char] : '';

    if (wordgame_is_finished($wordgame)) {
      $wordgame->status = 1;
      $push_message->data['finished'] = TRUE;
    }
    // Update games
    wordgame_save($wordgame);
    // Update point
    $user_level = wordgame_user_level();
    $user_level->point = $user_level->point + 1;
    wordgame_user_level_save($user_level);
    $push_message->data['point'] = $user_level->point;
	}
  nodejs_send_content_channel_message($push_message);
  drupal_json_output(array('data' => $push_message->data));
  exit;
}

/**
 * Menu callback function
 */
function wordgame_level($form , &$form_state) {
  if (!user_access('access game')) {
    drupal_goto('user');
  }
  $form['gamelevel'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('gamelevel')),
    '#attached' => array(
      'css' => array(drupal_get_path('module', 'wordgame') . "/css/wordgame.css")
    )
  );

  $form['gamelevel']['title'] = array(
    '#type' => 'markup',
    '#markup' => t('Please choose Level'),
    '#prefix' => '<h3>',
    '#suffix' => '</h3>'
  );

  $levels = wordgame_all_levels();

  $options = array();

  foreach ($levels as $level) {
    $options[$level->lid] = t($level->name);
  }
  $form['gamelevel']['level'] = array(
    '#type' => 'radios',
    '#options' => $options,
    '#default_value' => array('1')
  );
  $form['gamelevel']['actions']['#type'] = 'actions';
  $form['gamelevel']['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Play')
  );
  return $form;
}

/**
 * Submit callback function
 */
function wordgame_level_submit($form , &$form_state) {
  global $user;

  $lid = $form_state['values']['level'];
  $level = wordgame_user_level();
  if (!$level) {
    $level = (object) array(
      'uid' => $user->uid,
      'point' => 0,
      'played' => 0
    );
  }
  $level->lid = $lid;

  if (!empty($level->wuid)) {
    drupal_write_record('wordgame_user', $level, array('wuid'));
  }
  else {
    drupal_write_record('wordgame_user', $level);
  }
  $wordgame = wordgame_latest_games();
  wordgame_set_status($wordgame->wgid, 1);
  $form_state['redirect'] = 'wordgame';
}

/**
 * Menu callback function
 */
function wordgame_skip() {
  $wordgame = wordgame_latest_games();
  wordgame_set_status($wordgame->wgid, 1);
  drupal_goto('wordgame');
}

/**
 * Set wordgame status
 */
function wordgame_set_status($wgid, $status) {
  db_update('wordgame')->fields(array('status' => $status))->condition('wgid', $wgid)->execute();
}